package com.css.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.css.service.ICarService;
import com.css.vo.Car;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CarAction extends ActionSupport {

	private Car car;
	private List<Car> carList;
	private ICarService carService;
	private Integer carId;

	public Car getCar() {
		return car;
	}

	public void setCar(Car car) {
		this.car = car;
	}

	public ICarService getCarService() {
		return carService;
	}

	public void setCarService(ICarService carService) {
		this.carService = carService;
	}

	public String execute() throws Exception {
		return SUCCESS;
	}

	public String addCar() {
		try {
			carService.save(car);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String findAllCar() {
		try {
			carList = carService.findAllCar();
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String deleteCar() {
		try {
			HttpServletRequest request = (HttpServletRequest) ActionContext
					.getContext().get(ServletActionContext.HTTP_REQUEST);
			String carIdStr = request.getParameter("carId");
			Integer carId = Integer.parseInt(carIdStr);
			Car car = carService.findById(carId);

			carService.delete(car);
			return SUCCESS;

		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String updateCarView() {
		try {
			HttpServletRequest request = (HttpServletRequest) ActionContext
					.getContext().get(ServletActionContext.HTTP_REQUEST);
			String carIdStr = request.getParameter("carId");
			Integer carId = Integer.parseInt(carIdStr);
			car = carService.findById(carId);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String updateCar() {
		try {
			carService.update(car);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	private String keyword;

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String searchCar() {
		try {
			if (keyword != null && !keyword.trim().isEmpty()) {
				carList = carService.searchCar(keyword);
			} else {
				carList = carService.findAllCar();
			}
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

}
